package com.boguan.quartz.task;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boguan.common.constant.Constants;
import com.boguan.common.core.domain.entity.SysUser;
import com.boguan.common.core.redis.RedisCache;
import com.boguan.common.utils.SMSVerification;
import com.boguan.common.utils.StringUtils;
import com.boguan.common.utils.http.HttpUtils;
import com.boguan.device.domain.*;
import com.boguan.device.service.IDeviceAlarmService;
import com.boguan.device.service.IDeviceService;
import com.boguan.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component("deviceTask")
public class DeviceTask {

    private static final Logger logger = LoggerFactory.getLogger(DeviceTask.class);

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private IDeviceAlarmService deviceAlarmService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    public JPushClient jPushClient;


    @Autowired
    private SMSVerification smsVerification;


    /**
     * 获取刷新认证信息
     * 配置  50 分钟一次
     */
    public void getToken() {
        String url = "http://es.sunshy.cn:8089/api/Auth?appId=2464caee&secret=c1c09290";
//        String paramstr = "appId=2464caee&secret=c1c09290";
        String auth = HttpUtils.sendPost(url, null);
        JSONObject jsonObject = JSONObject.parseObject(auth);
        redisCache.setCacheObject("BaseAccessToken1", jsonObject, 50 * 60, TimeUnit.SECONDS);
    }


    /**
     * 根据设备编号 请求设备信息
     */
    public void getDevice() {
        List<Device> list = deviceService.selectDeviceByTypeId(20L);
        JSONObject jsonObject = redisCache.getCacheObject("BaseAccessToken1");
        if (StringUtils.isNull(jsonObject)) {
            getToken();
            jsonObject = redisCache.getCacheObject("BaseAccessToken1");
        }
        String url = "http://es.sunshy.cn:8089/api/Ru/GetRealMainsOfMeter";
        String auth = jsonObject.getString("TokenType") + " " + jsonObject.getString("AccessToken");
        for (Device device : list) {
            if (device.getForbidden()) {
                String[] split = device.getDeviceNum().split("-");
                if (split.length >= 2) {
                    String customerID = split[split.length - 2];
                    String meterID = split[split.length - 1];
                    String param = "pageIndex=0&pageSize=1" +
                            "&dealerID=" + jsonObject.getString("DealerID") +
                            "&customerID=" + customerID +
                            "&meterID=" + meterID;
                    String result = HttpUtils.sendGetBaseAuth(url, param, Constants.UTF8, auth);
                    JSONObject deviceResult = JSONObject.parseObject(result);
                    if (StringUtils.isNotNull(deviceResult)) {


                        JSONArray data = deviceResult.getJSONArray("Data");
                        if (StringUtils.isNotNull(data) && data.size() > 0) {
                            JSONObject deviceA = data.getJSONObject(0);
                            String integer = redisCache.getCacheObject(device.getDeviceNum() + "number:RmID");
                            String rmID = deviceA.getString("RmID");
                            deviceService.updateDevice(device);
                            Date theTime = deviceA.getDate("TheTime");
                            if (!rmID.equals(integer)) {
                                JSONArray realDetails = deviceA.getJSONArray("RealDetails");
                                redisCache.setCacheObject(device.getDeviceNum() + "number:RmID", rmID);
                                for (int i = 0; i < realDetails.size(); i++) {
                                    JSONObject deviceParam = realDetails.getJSONObject(i);
                                    for (DeviceParam deviceParam1 : device.getDeviceParams()) {
                                        String value = deviceParam.getString("TheValue");
                                        String dataType = deviceParam.getString("DataType");
                                        String keyCode = deviceParam.getString("KeyCode");
                                        if (dataType.equals("bit")) {
                                            value = value.substring(0, value.lastIndexOf("."));
                                        }
                                        if (keyCode.equals(deviceParam1.getIdentifier())) {
                                            if (deviceParam1.getId() != null) {
                                                //删除原来的key
                                                deviceParam1.setValue(value);
                                                deviceParam1.setTypeId(device.getTypeId());
                                                deviceParam1.setDeviceId(device.getDeviceId());
                                                deviceService.updateDeviceParam(deviceParam1);
                                            } else {
                                                deviceParam1.setValue(value);
                                                deviceParam1.setTypeId(device.getTypeId());
                                                deviceParam1.setDeviceId(device.getDeviceId());
                                                deviceService.insertSelective(deviceParam1);
                                            }
                                            DevicePastRecords pastRecords = new DevicePastRecords();
                                            pastRecords.setDeviceId(device.getDeviceId());
                                            pastRecords.setIdentifier(deviceParam1.getIdentifier());
                                            pastRecords.setParamId(deviceParam1.getParamId());
                                            pastRecords.setParamName(deviceParam1.getParamName());
                                            pastRecords.setParamType(deviceParam1.getParamType().toString());
                                            pastRecords.setTime(theTime);
                                            pastRecords.setValue(value);
                                            deviceService.insertSelectivePastRecords(pastRecords);
                                            //结束内循环
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 根据设备编号请求报警
     */
    public void getDeviceAlarm() {
        List<Device> list = deviceService.selectDeviceByTypeId(20L);
        JSONObject jsonObject = redisCache.getCacheObject("BaseAccessToken1");
        if (StringUtils.isNull(jsonObject)) {
            getToken();
            jsonObject = redisCache.getCacheObject("BaseAccessToken1");
        }
        String url = "http://es.sunshy.cn:8089/api/ru/PageAlarmsOfOperator";
        String auth = jsonObject.getString("TokenType") + " " + jsonObject.getString("AccessToken");
        for (Device device : list) {
            if (device.getForbidden()) {
                String[] split = device.getDeviceNum().split("-");
                if (split.length >= 2) {
                    String customerID = split[split.length - 2];
                    String meterID = split[split.length - 1];
                    String param = "isRead=false&pageIndex=0&pageSize=5" +
                            "&dealerID=" + jsonObject.getString("DealerID") +
                            "&customerID=" + customerID +
                            "&meterID=" + meterID;
                    String result = HttpUtils.sendGetBaseAuth(url, param, Constants.UTF8, auth);
                    JSONObject deviceResult = JSONObject.parseObject(result);
                    if (StringUtils.isNotNull(deviceResult)) {
                        JSONArray data = deviceResult.getJSONArray("Data");
                        for (int i = 0; i < data.size(); i++) {
                            JSONObject alarm = data.getJSONObject(i);
                            String alarmID = alarm.getString("AlarmID");
                            Date startTime = alarm.getDate("StartTime");
                            Date lastTime = alarm.getDate("LastTime");
                            String Content = alarm.getString("Content");
                            DeviceAlarmLog deviceAlarmLogs = deviceAlarmService.selectAlarmByError(device.getDeviceId(), alarmID, null, null);
                            if (StringUtils.isNotNull(deviceAlarmLogs)) {

//                    deviceAlarmLogs.setValue(event.getString("val"));
                                deviceAlarmLogs.setRecoverTime(lastTime);
                                deviceAlarmService.updateByPrimaryKeySelective(deviceAlarmLogs);
                            } else {
                                deviceAlarmLogs = new DeviceAlarmLog();
                                deviceAlarmLogs.setDeviceId(device.getDeviceId());
                                deviceAlarmLogs.setAlarmTime(startTime);
                                deviceAlarmLogs.setAlarmLevel(3);
                                deviceAlarmLogs.setErrorState(1);
                                deviceAlarmLogs.setRecoverTime(lastTime);
                                deviceAlarmLogs.setAlarmCause(Content);
                                deviceAlarmLogs.setIdentifier(alarmID);
                                deviceAlarmLogs.setErrorState(2);
//                    deviceAlarmLogs.setParamName(deviceParam.getParamName());
//                    deviceAlarmLogs.setValue(event.getString("val"));
                                deviceAlarmLogs.setStatus(1);
                                deviceAlarmLogs.setAlarmLocation(device.getLocaltion());
                                deviceAlarmLogs.setCreateTime(new Date());
                                deviceAlarmService.insertSelective(deviceAlarmLogs);
                                //根据部门id查询出部门的同级用户
                                List<SysUser> sysUsers = userService.selectUserByDeptId(device.getDeptId());
                                Set<String> usernames = new HashSet<>();
                                for (SysUser sysUser : sysUsers) {
                                    usernames.add(sysUser.getUserName());
                                }
                                if (usernames.size() <= 0) {
                                    usernames.add("admin");
                                }
                                PushPayload payload = PushPayload.newBuilder()
                                        .setPlatform(Platform.all())
                                        .setAudience(Audience.alias(usernames))
                                        .setNotification(Notification.alert(deviceAlarmLogs.getAlarmCause()))
                                        .build();

                                try {
                                    PushResult pushResult = jPushClient.sendPush(payload);
                                    logger.info("error:{}", pushResult.error);
                                    logger.info("sendno:{}", pushResult.sendno);
                                    logger.info("msg_id:{}", pushResult.msg_id);
                                    logger.info("statusCode:{}", pushResult.statusCode);
                                } catch (APIConnectionException | APIRequestException e) {
                                    e.printStackTrace();
                                }
                                //短息推送
                                List<DeviceAlarmInform> deviceAlarmInforms = deviceService.selectDeviceAlarmConfig(device.getDeviceId());
                                for (DeviceAlarmInform deviceAlarmInform : deviceAlarmInforms) {
                                    smsVerification.sendAlarm("及时星",
                                            deviceAlarmInform.getPhonenumber(),
                                            "SMS_210060127",
                                            "{\"deviceNum\":\"" + device.getDeviceNum() + "\",\"deviceName\":\"" + device.getDeviceName() + "\",\"name\":\"" + "'" + deviceAlarmInform.getUsername() + "'" + "\",\"msg\":\"" + deviceAlarmLogs.getAlarmCause() + "\"}");
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 根据设备编号请求故障
     */
    public void getDeviceFault() {
        List<Device> list = deviceService.selectDeviceByTypeId(20L);
        JSONObject jsonObject = redisCache.getCacheObject("BaseAccessToken1");
        if (StringUtils.isNull(jsonObject)) {
            getToken();
            jsonObject = redisCache.getCacheObject("BaseAccessToken1");
        }
        String url = "http://es.sunshy.cn:8089/api/ru/PageFaultsOfOperator";
        String auth = jsonObject.getString("TokenType") + " " + jsonObject.getString("AccessToken");
        for (Device device : list) {
            if (device.getForbidden()) {
                String[] split = device.getDeviceNum().split("-");
                if (split.length >= 2) {
                    String customerID = split[split.length - 2];
                    String meterID = split[split.length - 1];
                    String param = "isRead=false&pageIndex=0&pageSize=5" +
                            "&dealerID=" + jsonObject.getString("DealerID") +
                            "&customerID=" + customerID +
                            "&meterID=" + meterID;
                    String result = HttpUtils.sendGetBaseAuth(url, param, Constants.UTF8, auth);
                    JSONObject deviceResult = JSONObject.parseObject(result);
                    if (StringUtils.isNotNull(deviceResult)) {
                        JSONArray data = deviceResult.getJSONArray("Data");
                        for (int i = 0; i < data.size(); i++) {
                            JSONObject alarm = data.getJSONObject(i);
                            String faultID = alarm.getString("FaultID");
                            String Content = alarm.getString("Content");
                            String alarmID = alarm.getString("AlarmID");
                            Date startTime = alarm.getDate("StartTime");
                            Date lastTime = alarm.getDate("LastTime");
                            String checkFaultId = redisCache.getCacheObject(device.getDeviceNum() + "faultId");
                            if (faultID.equals(checkFaultId)) {
                                break;
                            }
                            redisCache.setCacheObject(device.getDeviceNum() + "faultId", faultID);
                            DeviceAlarmLog deviceAlarmLogs = deviceAlarmService.selectAlarmByError(device.getDeviceId(), faultID, null, null);
                            if (StringUtils.isNotNull(deviceAlarmLogs)) {

//                    deviceAlarmLogs.setValue(event.getString("val"));
                                deviceAlarmLogs.setRecoverTime(lastTime);
                                deviceAlarmService.updateByPrimaryKeySelective(deviceAlarmLogs);
                            } else {
                                deviceAlarmLogs = new DeviceAlarmLog();
                                deviceAlarmLogs.setDeviceId(device.getDeviceId());
                                deviceAlarmLogs.setAlarmTime(startTime);
                                deviceAlarmLogs.setAlarmLevel(4);//设备故障
                                deviceAlarmLogs.setErrorState(1);
                                deviceAlarmLogs.setRecoverTime(lastTime);
                                deviceAlarmLogs.setAlarmCause(Content);
                                deviceAlarmLogs.setIdentifier(alarmID);
                                deviceAlarmLogs.setErrorState(2);
//                    deviceAlarmLogs.setParamName(deviceParam.getParamName());
//                    deviceAlarmLogs.setValue(event.getString("val"));
                                deviceAlarmLogs.setStatus(1);
                                deviceAlarmLogs.setAlarmLocation(device.getLocaltion());
                                deviceAlarmLogs.setCreateTime(new Date());
                                deviceAlarmService.insertSelective(deviceAlarmLogs);
                                //根据部门id查询出部门的同级用户
                                List<SysUser> sysUsers = userService.selectUserByDeptId(device.getDeptId());
                                Set<String> usernames = new HashSet<>();
                                for (SysUser sysUser : sysUsers) {
                                    usernames.add(sysUser.getUserName());
                                }
                                if (usernames.size() <= 0) {
                                    usernames.add("admin");
                                }
                                PushPayload payload = PushPayload.newBuilder()
                                        .setPlatform(Platform.all())
                                        .setAudience(Audience.alias(usernames))
                                        .setNotification(Notification.alert(deviceAlarmLogs.getAlarmCause()))
                                        .build();

                                try {
                                    PushResult pushResult = jPushClient.sendPush(payload);
                                    logger.info("error:{}", pushResult.error);
                                    logger.info("sendno:{}", pushResult.sendno);
                                    logger.info("msg_id:{}", pushResult.msg_id);
                                    logger.info("statusCode:{}", pushResult.statusCode);
                                } catch (APIConnectionException | APIRequestException e) {
                                    e.printStackTrace();
                                }
                                //短息推送
                                List<DeviceAlarmInform> deviceAlarmInforms = deviceService.selectDeviceAlarmConfig(device.getDeviceId());
                                for (DeviceAlarmInform deviceAlarmInform : deviceAlarmInforms) {
                                    smsVerification.sendAlarm("及时星",
                                            deviceAlarmInform.getPhonenumber(),
                                            "SMS_210060127",
                                            "{\"deviceNum\":\"" + device.getDeviceNum() + "\",\"deviceName\":\"" + device.getDeviceName() + "\",\"name\":\"" + "'" + deviceAlarmInform.getUsername() + "'" + "\",\"msg\":\"" + deviceAlarmLogs.getAlarmCause() + "\"}");
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

